/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.plechinger.mcremote.server.craft;

import com.plechinger.mcremote.server.Server;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lukas
 */
public class CraftServer {

    private static CraftServer server = null;
    private long startTime;

    public static CraftServer getServer() {
        if (server == null) {
            server = new CraftServer();
        }
        return server;
    }
    CraftController controller;

    private CraftServer() {
        try {
            controller = new CraftController(Server.getServer().getProperties());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized List<CraftLogElement> getLog() {
        return controller.getLog();
    }

    public void start() throws CraftServerStatusException {
        controller.start();
        startTime = System.currentTimeMillis();
    }

    public void stop() throws CraftServerStatusException {
        controller.stop();
        startTime=0;
    }

    public boolean isStarted() {
        return controller.isStarted();
    }

    public long getRuntime() {
        if(startTime==0){
            return 0;
        }
        return System.currentTimeMillis()-startTime;
    }

    public List<String> playerList() throws CraftServerStatusException, CraftServerTimeoutException {
        List<String> players = new ArrayList<String>();
        List<CraftLogElement> log = controller.command(CraftCommand.LIST);
        String playersString = log.get(0).getMessage();
        playersString = playersString.substring(19);
        String[] pl = playersString.split("[,]");
        for (int i = 0; i < pl.length; i++) {
            if (!"".equals(pl[i])) {
                players.add(pl[i]);
            }
        }
        return players;
    }

    public static void main(String[] args) throws Exception {
        getServer().start();

        try {
            Thread.sleep(10000);
        } catch (Exception e) {
        }
        System.out.println(getServer().playerList());
        getServer().stop();
    }
}
